export const varType = {
  types: ['Array', 'Number', 'Boolean', 'Object', 'String', 'Undefined', 'Null', 'NaN', 'Function'],
  typeCall: o => Object.prototype.toString.call(o),
  init() {
    varType.types.map(item => {
      let key = `is${item}`;
      let fn = varType[key] = function (val) {
        if (item === 'NaN') return Number.isNaN(val);
        return varType.typeCall(val) === `[object ${item}]`;
      }
      this[key] = fn;
    })
  }
}
/*UUID*/
export function UUID() {
  let d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
    d += performance.now();
  }
  let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

export function httpToHttps(url) {
  return url.replace(/http/, 'https');
}

export function urlToImageElement(src, {pixel}) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.setAttribute("crossOrigin", 'Anonymous');
    image.onerror = reject;
    image.onload = () => {
      if (pixel) {
        const w = image.width;
        if (image.width > pixel) {
          image.width = pixel;
        }
        image.height = image.height * (image.width / w);
      }else if(image.width > 1300) {
        pixel = 1300
        if (pixel) {
          const w = image.width;
          if (image.width > pixel) {
            image.width = pixel;
          }
          image.height = image.height * (image.width / w);
        }
      }
      resolve(image)
    }
    image.src = src;
  })
}

export function drawImgToCanvas(cxt, image, x, y, width, height) {
  cxt.drawImage(image, x, y, width, height)
}

export function canvasToImage(canvas, type = 'image/png', encoderOptions = 0.92) {
  return canvas.toDataURL(type, encoderOptions);
}

export function download(Blob, filename) {
  const ele = document.createElement('a');
  ele.download = filename;
  ele.style.display = 'none';
  ele.href = window.URL.createObjectURL(Blob);
  document.body.appendChild(ele);
  ele.click();
  document.body.removeChild(ele);
  window.URL.revokeObjectURL(Blob);
}

export function base64ToBlob(base64) {
  let arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
    str = atob(arr[1]), n = str.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = str.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime})
}
export const C = {}
/*
* 获取鼠标在元素上的坐标
* */
C.getOffset = function (el, scale = 1) {
  let mouse = {x: 0, y: 0}
  el.addEventListener('mousemove', function (e) {
    let {x, y} = C.eventWrapper(e)
    mouse.x = x * scale
    mouse.y = y * scale
  })
  return mouse
}

/*
* 坐标转换
* */
C.eventWrapper = function (event, scale = 1) {
  let {pageX, pageY, target} = event;
  let {left, top} = target.getBoundingClientRect()
  return {x: (pageX - left) * scale, y: (pageY - top) * scale}
}

/*
* 角度转弧度
* */
C.toRad = function (angle) {
  return angle * Math.PI / 180
}

/*
* 弧度转角度
* */
C.toAngle = function (rad) {
  return rad * 180 / Math.PI
}

export function getImageData(canvas, width, height) {
  let ctx = canvas.getContext('2d');
  if(!width){
    width = canvas.width
  }
  if(!height){
    height = canvas.height
  }
  return ctx.getImageData(0, 0, width, height)
}

/*绘制圆*/
export function drawCircle(ctx, x, y, w, h, color, lineWidth) {
  let c_x = x + (w + 1) / 2;
  let c_y = y + (h + 1) / 2;
  let a = (w - 6) / 2;
  let b = (h - 6) / 2;
  let r = (a > b) ? a : b;
  let ratioX = a / r; //横轴缩放比率
  let ratioY = b / r; //纵轴缩放比率
  if (r > 0) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.save();
    ctx.scale(ratioX, ratioY); //进行缩放（均匀压缩）
    ctx.beginPath();
    //从椭圆的左端点开始逆时针绘制
    ctx.moveTo((c_x + a) / ratioX, c_y / ratioY);
    ctx.arc(c_x / ratioX, c_y / ratioY, r, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
    ctx.stroke();
  }
}

/*绘制箭头*/
export function lineArrow(ctx, start, end, color, lineWidth) {
  //设置线的粗细和断点，转角样式
  ctx.strokeStyle = color
  ctx.fillStyle = color
  ctx.lineWidth = lineWidth
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'

  //计算两点距离，主要是为了计算斜率
  let distanceX = end.x - start.x, distanceY = end.y - start.y;
  let distance = Math.sqrt(distanceY * distanceY + distanceX * distanceX);
  //箭头的尺寸
  let distanceArrow = 16, sharpeArrow = 6;
  //先确定轴线与三角两个尖角点交汇坐标
  let arrowLineTo = {
    x: end.x - distanceArrow * distanceX / distance,
    y: end.y - distanceArrow * distanceY / distance
  };
  let arrowTo3 = {
    x: arrowLineTo.x - sharpeArrow * distanceY / distance,
    y: arrowLineTo.y + sharpeArrow * distanceX / distance
  };
  let arrowTo4 = {
    x: arrowLineTo.x + sharpeArrow * distanceY / distance,
    y: arrowLineTo.y - sharpeArrow * distanceX / distance
  };
  //登录状态下不会出现这行文字，点击页面右上角一键登录
  //开始绘制
  ctx.beginPath();
  ctx.moveTo(start.x, start.y);
  ctx.lineTo(end.x, end.y);
  // 两个结束对称点
  ctx.lineTo(arrowTo3.x, arrowTo3.y);
  ctx.lineTo(arrowTo4.x, arrowTo4.y);
  // 回到结束点
  ctx.lineTo(end.x, end.y);
  // 闭合，描边与填充
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

/*划线*/
export function drawPen(ctx, s, e, color, lineWidth){
  ctx.beginPath();
  ctx.moveTo(s.x, s.y);
  ctx.lineTo(e.x, e.y);
  ctx.strokeStyle = color;
  ctx.lineWidth = lineWidth;
  ctx.lineCap = "round";
  ctx.linJoin = "round";
  ctx.stroke();
}

export const keyCode = {
    c: 67,
    d: 68,
    q: 81,
    t: 84,
    l: 76,
    p: 80,
    r: 82,
    z: 90,
    "-": 189,
    "+": 187,
    ctrl: 17
}
/**
 * Ctrl + Q 方框
 * Ctrl + C 圆
 * Ctrl + L 线
 * Ctrl + P 笔
 * Ctrl + T 文本
 * Ctrl + R 旋转
 * Ctrl + + 放大
 * Ctrl + - 缩小
 * Ctrl + D 下载
 * Ctrl + Z 撤销
 * */
function eventKeys(fn){
    let k1 = null, k2 = null, k = 0;
    window.addEventListener('keyup', upFn)
    window.addEventListener('keydown', downFn)
    function upFn(){
        k = 0
        k1 = k2 = null
    }
    function downFn(e){
        console.log('111', k1, k2, k)
        e = e || window.event;
        if(k === 1 && !k2 && e.keyCode !== k1){
            k2 = e.keyCode
            k = 2
            fn(k1, k2, e)
        }else if(k === 0 && !k1){
            k1 = e.keyCode
            k = 1
        }
    }
}
export function shortcutKeys(key, fn){
    if(!key){
        return console.log('快捷键key无效~')
    }
    let k = key.toLocaleLowerCase().replace(/\s/g, '').split('+')
    let k_1 = keyCode[k[0]];
    let k_2 = keyCode[k[1]];
    if(!k_1 || !k_2){
        return console.error('无此快捷键:' + key)
    }
    eventKeys((k1, k2, e) => {
        if(k_1 === k1 && k_2 === k2){
            fn(e)
        }
    })
}









